<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="链接名称" prop="weLinkName">
        <el-input
          v-model="queryParams.weLinkName"
          placeholder="请输入企微获客链接名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-260px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
    </el-form>
    <div class="flex justify-between">
      <div>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button type="primary" plain @click="handleSync">
          <Icon icon="ep:switch" class="mr-5px" />
          同步获客链接
        </el-button>
        <el-button
          type="primary"
          @click="openForm('create')"
          v-hasPermi="['wecom:acq-link:create']"
          class="ml-10px"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="primary" @click="saveImg" v-loading="loading2"
          ><el-icon class="mr-5px"><Picture /></el-icon>保存为图片</el-button
        >
        <el-button @click="toggleActionsVisible" :icon="actionsVisible ? Close : View">
          {{ actionsVisible ? '隐藏操作栏' : '显示操作栏' }}
        </el-button>
      </div>
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div id="table_box_2">
      <el-table
        v-loading="loading"
        :data="list"
        :stripe="true"
        border
        :show-overflow-tooltip="true"
      >
        <el-table-column
          label="企微获客链接名称"
          align="center"
          prop="weLinkName"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-text
              style="cursor: pointer"
              @click="checkQrcode(scope.row.weLinkUrl, scope.row.createTime)"
              type="primary"
              >{{ scope.row.weLinkName }}</el-text
            >
          </template>
        </el-table-column>
        <el-table-column label="0-2" align="center" prop="weLinkName2">
          <template #default="scope">{{ scope.row.weLinkName2 }} </template>
        </el-table-column>
        <el-table-column label="2-4" align="center" prop="weLinkName2">
          <template #default="scope">{{ scope.row.weLinkName2 }} </template>
        </el-table-column>
        <el-table-column label="4-6" align="center" prop="weLinkName2">
          <template #default="scope">{{ scope.row.weLinkName2 }} </template>
        </el-table-column>
        <el-table-column label="6-8" align="center" prop="weLinkName2">
          <template #default="scope">{{ scope.row.weLinkName2 }} </template>
        </el-table-column>
        <el-table-column label="8-10" align="center" prop="weLinkName2">
          <template #default="scope">{{ scope.row.weLinkName2 }} </template>
        </el-table-column>
        <el-table-column label="10-12" align="center" prop="weLinkName2">
          <template #default="scope">{{ scope.row.weLinkName2 }} </template>
        </el-table-column>
        <el-table-column label="12-14" align="center" prop="weLinkName2">
          <template #default="scope">{{ scope.row.weLinkName2 }} </template>
        </el-table-column>
        <el-table-column label="14-16" align="center" prop="weLinkName2">
          <template #default="scope">{{ scope.row.weLinkName2 }} </template>
        </el-table-column>
        <el-table-column label="16-18" align="center" prop="weLinkName2">
          <template #default="scope">{{ scope.row.weLinkName2 }} </template>
        </el-table-column>
        <el-table-column label="18-20" align="center" prop="weLinkName2">
          <template #default="scope">{{ scope.row.weLinkName2 }} </template>
        </el-table-column>
        <el-table-column label="20-22" align="center" prop="weLinkName2">
          <template #default="scope">{{ scope.row.weLinkName2 }} </template>
        </el-table-column>
        <el-table-column label="22-24" align="center" prop="weLinkName2">
          <template #default="scope">{{ scope.row.weLinkName2 }} </template>
        </el-table-column>
        <el-table-column label="今日总数" align="center" prop="weLinkName3" />
        <el-table-column label="近30天点击次数" align="center">
          <template #default="scope">
            <span>{{ useStat[scope.row.weLinkId]?.clickCount ?? '--' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="近30天新增客户" align="center">
          <template #default="scope">
            <span>{{ useStat[scope.row.weLinkId]?.newCount ?? '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="120"
          fixed="right"
          v-if="actionsVisible"
        >
          <template #default="scope">
            <el-dropdown>
              <el-button type="primary" size="small" link> 设置 </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-hasPermi="['wecom:acq-link:update']"
                    @click="openForm('update', scope.row.id)"
                  >
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item @click="openCustomerList(scope.row.weLinkId)">
                    查看客户列表
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-hasPermi="['wecom:acq-link:delete']"
                    @click="handleDetele(scope.row.id)"
                    style="color: var(--el-color-danger)"
                  >
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 展示形式：二维码 URL -->
  <Dialog
    title="二维码"
    v-model="qrCodeVisible"
    width="350px"
    append-to-body
    :close-on-press-escape="false"
  >
    <Qrcode id="qr_code" @done="onCodeDone" :text="qrCodeLink" :width="310" />
    <div class="mb-10px flex items-center">
      <el-text style="flex-shrink: 0">链接：</el-text>
      <div class="boxs">
        <el-text>{{ url }}</el-text>
      </div>
      <el-icon
        color="#0052cc"
        class="ml-10px"
        size="18"
        @click="copyQrcode(url)"
        style="cursor: pointer"
      >
        <CopyDocument></CopyDocument>
      </el-icon>
    </div>
    <div class="mb-10px">
      <el-text>创建时间：{{ formatDate(times) }}</el-text>
    </div>
    <el-row class="justify-center">
      <el-button @click="downloadQrcode" type="primary">下载二维码</el-button>
    </el-row>
  </Dialog>

  <!-- 新增、编辑 -->
  <AcqLinkForm ref="acqLinkFormRef" @success="getList" />

  <CustomerList ref="customerRef" />
</template>

<script setup lang="ts">
import * as AcqLinkApi from '@/api/wecom/acqlink'
import { dateFormatter } from '@/utils/formatTime'
import { Qrcode } from '@/components/Qrcode'
import { useClipboard } from '@vueuse/core'
import CustomerList from './CustomerList.vue'
import AcqLinkForm from './AcqLinkForm.vue'
import { Picture, Close, View, CopyDocument } from '@element-plus/icons-vue'
import html2canvas from 'html2canvas'
import { formatDate } from '@/utils/formatTime'

defineOptions({ name: 'AcqLink' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

const weLinkIds = ref([])
const useStat = ref({})
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AcqLinkApi.getAcqLinkPage(queryParams)
    list.value = data.list
    weLinkIds.value = []
    list.value.map((i) => {
      weLinkIds.value.push(i.weLinkId)
    })
    useStat.value = await AcqLinkApi.getUseStat({
      weLinkIds: weLinkIds.value
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 新增编辑 */
const acqLinkFormRef = ref()
const openForm = (type: string, id?: number) => {
  acqLinkFormRef.value.open(type, id)
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 删除按钮操作 */
const handleDetele = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AcqLinkApi.deleteAcqLink(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 同步获客链接 */
const handleSync = async () => {
  const data = await AcqLinkApi.syncAcqLink()
  if (data) {
    message.success(t('同步成功'))
    await getList()
  } else {
    message.error(t('同步有误'))
  }
}

const url = ref(null)
const times = ref(null)
const qrCodeVisible = ref(false)
const qrCodeLink = ref(null)
/** 查看二维码 */
const checkQrcode = (link, time) => {
  times.value = time
  url.value = link
  qrCodeLink.value = link
  qrCodeVisible.value = true
}
const qrCodeValue = ref()
const onCodeDone = (e) => {
  qrCodeValue.value = e
}
/** copyQrcode */
const copyQrcode = async (link) => {
  const { copy, copied, isSupported } = useClipboard({ source: link })
  if (!isSupported) {
    message.error(t('common.copyError'))
    return
  }
  await copy()
  if (unref(copied)) {
    message.success(t('common.copySuccess'))
  }
}

/** 下载二维码 */
const downloadQrcode = () => {
  let save = document.createElement('a')
  save.href = qrCodeValue.value
  // 下载的名字
  save.download = '获客链接二维码.png'
  // 直接回调a的点击事件
  save.click()
}

const customerRef = ref(false) // 弹窗的是否展示
const openCustomerList = (id: number) => {
  customerRef.value.open(id)
}
// base64转blob方法
const dataURIToBlob = (dataURI) => {
  let binStr = atob(dataURI.split(',')[1]),
    len = binStr.length,
    arr = new Uint8Array(len)

  for (var i = 0; i < len; i++) {
    arr[i] = binStr.charCodeAt(i)
  }
  return new Blob([arr])
}
/*下载图片方法*/
const fileDownload = (downloadUrl) => {
  let aLink = document.createElement('a')
  aLink.style.display = 'none'
  // 以防base64过长导致下载失败，所以将base64转成blob格式
  aLink.href = URL.createObjectURL(dataURIToBlob(downloadUrl))
  aLink.download = `${new Date().toLocaleString()}.png`
  document.body.appendChild(aLink)
  aLink.click()
  document.body.removeChild(aLink)
}
const loading2 = ref(false)
const saveImg = () => {
  try {
    loading2.value = true
    let el = document.getElementById('table_box_2')
    let options = {
      width: el.offsetWidth,
      height: el.offsetHeight,
      useCORS: true, // 是否尝试使用 CORS 从服务器加载图像
      allowTaint: false, // 是否允许跨源图像污染画布
      backgroundColor: '#ffffff', // 必须设置背景（否则水印可能透明）
      scale: 1, // 禁止缩放（避免水印偏移）
      logging: true
    }
    html2canvas(el, options).then((canvas) => {
      var mergedCanvas = document.createElement('canvas')
      var context = mergedCanvas.getContext('2d')
      mergedCanvas.width = canvas.width
      mergedCanvas.height = canvas.height + 80 // 标题高度为50px，根据实际情况调整

      // 1. 填充白色背景（避免默认黑色）
      context.fillStyle = '#ffffff'
      context.fillRect(0, 0, mergedCanvas.width, mergedCanvas.height)

      // 2. 添加标题和时间（居中显示）
      context.fillStyle = '#000000' // 文字颜色
      context.font = 'bold 20px Arial' // 字体样式

      // 计算标题和时间文本的宽度
      const titleText = '企微获客链接统计表'
      const timeText = `生成时间: ${new Date().toLocaleString()}`
      const titleWidth = context.measureText(titleText).width
      const timeWidth = context.measureText(timeText).width

      // 绘制标题（居中）
      context.textAlign = 'center'
      context.fillText(titleText, canvas.width / 2, 35)

      // 绘制时间（居中，在标题下方）
      context.fillText(timeText, canvas.width / 2, 60)

      // 3. 添加原图内容
      context.drawImage(canvas, 0, 80) // 原图从y=50位置开始绘制

      let imgData = mergedCanvas.toDataURL('image/jpeg', 0.92)
      fileDownload(imgData)
      loading2.value = false
    })
  } catch {
    loading2.value = false
  }
}

const actionsVisible = ref(true)

const toggleActionsVisible = () => {
  actionsVisible.value = !actionsVisible.value
}
/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
<style scoped lang="scss">
.boxs {
  white-space: nowrap;
  overflow-x: auto;
  &::-webkit-scrollbar {
    height: 2px; /* 水平滚动条的高度（原垂直滚动条是 width） */
  }
  &::-webkit-scrollbar-track {
    background: #f1f1f1; /* 滚动条轨道颜色 */
  }
  &::-webkit-scrollbar-thumb {
    background: #d8d8d8; /* 滚动条滑块颜色 */
  }
  &::-webkit-scrollbar-thumb:hover {
    background: #d8d8d8; /* 滑块悬停颜色 */
  }
  /* 水平滚动条两端的圆角（可选） */
  &::-webkit-scrollbar-thumb:horizontal:start {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }
  &::-webkit-scrollbar-thumb:horizontal:end {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
  }
}
</style>
